package com.net.shard.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 *
 * @Description: <br>
 * @Project: hades <br>
 * @CreateDate: Created in 2018/7/20 15:16 <br>
 */
@Configuration
@ComponentScan({"com.net.shard"})
@MapperScan(basePackages = "com.net.shard.dao", sqlSessionFactoryRef = "commonSqlSessionFactory")
public class CommonDatabaseConfiguration {

    @Autowired
    private ResourceLoader resourceLoader;

    @Value("${spring.datasource.driver-class-name}")
    String driverClass;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String userName;
    @Value("${spring.datasource.password}")
    String passWord;


    @Bean("commonDataSource")
    @Primary
    public DataSource commonDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean commonSqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(commonDataSource());
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class); //必须的，否则spring boot启动的路径不正确
        sqlSessionFactoryBean.setConfigLocation(resourceLoader.getResource("classpath:shard-common-mybatis.xml"));

        return sqlSessionFactoryBean;
    }

    @Bean
    public DataSourceTransactionManager CommonTransactionManager() {
        return new DataSourceTransactionManager(commonDataSource());
    }
}
